import { gql } from '@apollo/client';

import { client } from '../index';

import {
  GET_CUSTOMERS_LIST,
  GET_CUSTOMER_DETAIL,
  REMOVE_CUSTOMER,
  UPDATE_CUSTOMER,
  SAVE_CUSTOMER,
} from './grapql';

import request from '@/utils/request';

import type {
  ICustomer,
  ListRequest,
  ListReponse,
  DetailReponse,
  OperateReponse,
} from './customer.d';

export async function getListDataService(params: ListRequest): Promise<ListReponse> {
  const res = await client.query({
    query: GET_CUSTOMERS_LIST,
    // Provide any required variables here
    variables: {
      ...params,
    },
    // Doesn't check cache before making a network request
    fetchPolicy: 'network-only',
    notifyOnNetworkStatusChange: true,
  });
  const { data, pageInfo } = res.data.customers;
  console.log(res);

  const newList = data.map((item: ICustomer) => ({ ...item, key: item.id }));

  // const res = await request('/graphql', CustomerList, { method: 'POST' });

  return new Promise((resolve) => {
    resolve({
      code: 200,
      message: null,
      data: {
        list: newList,
        pageInfo,
      },
    });
  });
}

// ------------

export async function getDetailByIdService(id: string): Promise<DetailReponse> {
  const res = await client.query({
    query: GET_CUSTOMER_DETAIL,
    // Provide any required variables here
    variables: { id },
    fetchPolicy: 'network-only',
  });

  // const res = await request('/graphql', CustomerList, { method: 'POST' });

  return new Promise((resolve) => {
    resolve({
      code: 200,
      message: null,
      data: res.data.customer.data,
    });
  });
}

export async function removeDataByIdService(id: string): Promise<OperateReponse> {
  const res = await client.mutate({
    mutation: REMOVE_CUSTOMER,
    variables: { id },
    // refetchQueries: [{ query: GET_CUSTOMERS_LIST }],
  });

  // const res = await request('/graphql', CustomerList, { method: 'POST' });

  return new Promise((resolve) => {
    resolve({ code: 200, message: null, data: res.data.removeCustomer });
  });
}

export async function updateDataService(params: ICustomer): Promise<OperateReponse> {
  const res = await client.mutate({
    mutation: UPDATE_CUSTOMER,
    variables: params,
    // refetchQueries: [{ query: GET_CUSTOMERS_LIST }],
  });

  // const res = await request('/graphql', CustomerList, { method: 'POST' });

  return new Promise((resolve) => {
    resolve({ code: 200, message: null, data: res.data.updateCustomer });
  });
}

// --------

export async function addDataService(params: ICustomer): Promise<OperateReponse> {
  const res = await client.mutate({
    mutation: SAVE_CUSTOMER,
    variables: params,
    // refetchQueries: [{ query: GET_CUSTOMERS_LIST }],
  });

  // const res = await request('/graphql', CustomerList, { method: 'POST' });

  return new Promise((resolve) => {
    resolve({ code: 200, message: null, data: res.data.addCustomer });
  });
}
